package team.ttorder.ttorder.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import team.ttorder.ttorder.javabean.PageBean;
import team.ttorder.ttorder.model.Food;
import team.ttorder.ttorder.model.FoodType;
import team.ttorder.ttorder.service.IFoodService;
import team.ttorder.ttorder.utils.ImageUtils;
import team.ttorder.ttorder.utils.LoggerUtil;

@RestController
@RequestMapping("/food")
public class FoodController {

	@Autowired
	private IFoodService foodService;

	@RequestMapping(value = "/manageFoods", method = RequestMethod.GET)
	public ModelAndView manageFood(ModelMap modelMap) {
		// modelMap.addAttribute("foods", foodService.getAllFoods());
		return new ModelAndView("business/food/manageFood");
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/findAllFoods", method = RequestMethod.POST)
	public PageBean getAllFoods(int pageNum, int pageSize) {
		PageBean<Food> result = foodService.getAllFood(pageNum, pageSize);
		return result;
	}

	@RequestMapping(value = "/getAllFoodType", method = RequestMethod.POST)
	public List<FoodType> getAllFoodType() {
		return foodService.getAllFoodType();
	}

	@RequestMapping(value = "/addFood", method = RequestMethod.POST)
	public ModelAndView addFood(@RequestParam(value = "image", required = false) MultipartFile file,
			HttpServletRequest request, RedirectAttributes redirectAttributes) {
		String newFileName = "";
		if (file != null) {
			LoggerUtil.LogINFO(this.getClass(), "文件不为空");
		}
		if (file != null && !file.isEmpty()) {
			// 如果小于20M
			if (20480 > file.getSize() / 1024) {
				String fileName = file.getOriginalFilename();
				String suffix = fileName.substring(fileName.lastIndexOf("."));
				if (suffix.equals(".jpg") || suffix.equals(".jpeg")) {
					newFileName = String.valueOf(System.currentTimeMillis()) + suffix;
					try {
						// String savePath = this.getClass().getResource("").toString();
						// 获取classpath的路径
						String savePath = this.getClass().getClassLoader().getResource("").getPath();
						LoggerUtil.LogINFO(this.getClass(), savePath);
						ImageUtils.save(newFileName, file, savePath);
						// 将数据写入到数据库中
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					redirectAttributes.addFlashAttribute("file", "");
					return new ModelAndView("redirect:/food/manageFoods");
				}
			} else {
				redirectAttributes.addFlashAttribute("message", "添加失败，图片大小大于20M");
				return new ModelAndView("redirect:/food/manageFoods");
			}
		}
		String price = request.getParameter("price");
		String mPrice = request.getParameter("mPrice");
		Food food = new Food();
		food.setFoodName(request.getParameter("foodName"));
		String describe = request.getParameter("describe");
		if (describe != null && describe != "") {
			food.setRemark(describe);
		}
		if (-1 == price.indexOf(",")) {
			food.setPrice(Float.valueOf(request.getParameter("price")));
		} else {
			String s = "";
			String[] array = price.split(",");
			for (int j = 0; j < array.length; j++) {
				s += array[j];
			}
			food.setPrice(Float.valueOf(s));
		}
		if (-1 == mPrice.indexOf(",")) {
			food.setPrice(Float.valueOf(request.getParameter("mPrice")));
		} else {
			String s = "";
			String[] array = price.split(",");
			for (int j = 0; j < array.length; j++) {
				s += array[j];
			}
			food.setmPrice(Float.valueOf(s));
		}
		food.setFoodTypeId(Integer.valueOf(request.getParameter("foodType")));
		food.setImage(newFileName);
		foodService.addFood(food);
		return new ModelAndView("redirect:/food/manageFoods");
	}

	@RequestMapping(value = "/updateFood", method = RequestMethod.POST)
	public ModelAndView updateFood(@RequestParam(value = "image", required = false) MultipartFile file,
			HttpServletRequest request, RedirectAttributes redirectAttributes) {
		Food food = foodService.getFoodById(Integer.valueOf(request.getParameter("id")));
		String newFileName = food.getImage();
		if (file != null && !file.isEmpty()) {
			if (20480 > file.getSize() / 1024) {
				String savePath = this.getClass().getClassLoader().getResource("").getPath();
				// 删除原来的文件
				ImageUtils.delete(savePath, newFileName);
				String fileName = file.getOriginalFilename();
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				newFileName = String.valueOf(System.currentTimeMillis()) + "." + suffix;
				try {
					// 保存新文件
					LoggerUtil.LogINFO(this.getClass(), savePath);
					ImageUtils.save(newFileName, file, savePath);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				redirectAttributes.addFlashAttribute("message", "添加失败，图片大小大于20M");
				return new ModelAndView("redirect:/food/manageFoods");
			}
		}
		// 将数据写入到数据库中
		String price = request.getParameter("price");
		String mPrice = request.getParameter("mPrice");
		food = new Food();
		food.setFoodName(request.getParameter("foodName"));
		String describe = request.getParameter("describe");
		if (describe != null && describe != "") {
			food.setRemark(describe);
		}
		if (-1 == price.indexOf(",")) {
			food.setPrice(Float.valueOf(request.getParameter("price")));
		} else {
			String s = "";
			String[] array = price.split(",");
			for (int j = 0; j < array.length; j++) {
				s += array[j];
			}
			food.setPrice(Float.valueOf(s));
		}
		if (-1 == mPrice.indexOf(",")) {
			food.setPrice(Float.valueOf(request.getParameter("mPrice")));
		} else {
			String s = "";
			String[] array = price.split(",");
			for (int j = 0; j < array.length; j++) {
				s += array[j];
			}
			food.setmPrice(Float.valueOf(s));
		}
		food.setFoodTypeId(Integer.valueOf(request.getParameter("foodType")));
		food.setImage(newFileName);
		foodService.updateFood(food);
		return new ModelAndView("redirect:/food/manageFoods");
	}

	/**
	 * 后端显示图片
	 */
	/*
	 * @RequestMapping(value = "/browseImage", method = RequestMethod.POST) public
	 * String browseImage(@RequestParam(value = "image", required = false)
	 * MultipartFile file) { if (file != null) { String fileName =
	 * file.getOriginalFilename(); String suffix =
	 * fileName.substring(fileName.lastIndexOf(".") + 1); String newFileName =
	 * String.valueOf(System.currentTimeMillis()) + "." + suffix;
	 * LoggerUtil.LogINFO(this.getClass(), fileName);
	 * LoggerUtil.LogINFO(this.getClass(), newFileName); suffix += ".jgp"; String
	 * savePath = this.getClass().getClassLoader().getResource("").getPath(); return
	 * ImageUtils.browseImage(newFileName, savePath, file); } return ""; }
	 */

	@RequestMapping(value = "/deleteFoodById/{id}")
	public ModelAndView deleteFoodById(@PathVariable("id") Integer id) {
		LoggerUtil.LogINFO(this.getClass(), id + "");
		foodService.deleteFoodById(id);
		return new ModelAndView("redirect:/food/manageFoods");
	}

	@RequestMapping(value = "/getFoodById", method = RequestMethod.POST)
	public Food getFoodById(Integer id) {
		return foodService.getFoodById(id);
	}

	@RequestMapping(value = "/getFoodTypeById")
	public FoodType getFoodTypeById(Integer id) {
		return foodService.getFoodTypeById(id);
	}

	@RequestMapping(value = "/addFoodType")
	public String addFoodType(FoodType foodType) {
		return foodService.addFoodType(foodType);
	}

	@RequestMapping(value = "/updateFoodType")
	public String updateFoodType(FoodType foodType) {
		return foodService.updateFoodType(foodType);

	}

	@RequestMapping(value = "/deleteFoodTypeById/{id}")
	public ModelAndView deleteFoodTypeById(@PathVariable("id") Integer id) {
		LoggerUtil.LogINFO(this.getClass(), id + "");
		foodService.deleteFoodTypeById(id);
		return new ModelAndView("redirect:/food/manageFoodTypes");
	}

	@RequestMapping(value = "/manageFoodTypes")
	public ModelAndView manageFoodType(Model model) {
		model.addAttribute("foodTypes", foodService.getAllFoodType());
		return new ModelAndView("business/food/manageFoodType");
	}

	@RequestMapping(value = "/getImage")
	public void getImage(@RequestParam(value = "image", required = false) String local, HttpServletResponse response) {
		if (local != null) {
			ImageUtils.getImage(response, local);
		}
	}
}
